/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ipo.mm.ejb.entities.City;
import org.ipo.mm.ejb.entities.Institution;
import org.ipo.mm.ejb.entities.InstitutionFamily;
import org.ipo.mm.ejb.entities.InstitutionRegion;
import org.ipo.mm.ejb.entities.InstitutionType;
import org.ipo.mm.ejb.facade.city.CityFacadeLocal;
import org.ipo.mm.ejb.facade.family.InstitutionFamilyFacadeLocal;
import org.ipo.mm.ejb.facade.institution.InstitutionFacadeLocal;
import org.ipo.mm.ejb.facade.meeting.MeetingFacadeLocal;
import org.ipo.mm.ejb.facade.region.InstitutionRegionFacadeLocal;
import org.ipo.mm.ejb.facade.type.InstitutionTypeFacadeLocal;
import org.ipo.mm.web.formbeans.MeetingSearchBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.pager.MeetingPager;

/**
 *
 * @author makcro
 */
public class MeetingSearchAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;

        MeetingPager pager = null;

        String pageNumber = request.getParameter("p");

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        String bcName = (pageNumber == null) ? ConstantManager.BC_MEETING_LIST : ConstantManager.BC_MEETING_LIST + "-" + pageNumber;
        bc.push(bcName, request);

        injectAdvSearchBaseData(request);

        //if this is true then user submited search or opend this page for the first time
        //anyway pager is created
        if (pageNumber == null) {


            String conclutionsFilter = null;
            String conclutionsOper = null;

            String dateIntervalEnd = null;
            String dateIntervalStart = null;

            String meetingNameFilter = null;
            String meetingNameOper = null;

            String orgNameFilter = null;
            String orgNameOper = null;

            String[] orgInstFilter = null;
            String[] orgITypeFilter = null;
            String[] orgIFamilyFilter = null;
            String[] orgIRegionFilter = null;
            String[] orgIdFilter = null;
            String repNameFilter = null;
            String repNameOper = null;

            String[] repInstFilter = null;
            String[] repITypeFilter = null;
            String[] repIFamilyFilter = null;
            String[] repIRegionFilter = null;
            String[] repIdFilter = null;

            String venueFilter = null;
            String venueOper = null;

            boolean isQuickSearch = false;

            String orderByClause = null;

            Date startDate = null;
            Date endDate = null;

            //user clicked on quicklink
            String rid = request.getParameter("rid");
            String iid = request.getParameter("iid");
            String orderByParam = request.getParameter("orderBy");

            if (rid != null) {
                orgIdFilter = new String[]{rid};
                repIdFilter = new String[]{rid};
                isQuickSearch = true;
            } else if (iid != null) {
                orgInstFilter = new String[]{iid};
                repInstFilter = new String[]{iid};
                isQuickSearch = true;
            }
            else if(orderByParam != null){

            }
            //user submited advanced search form
            else {
                MeetingSearchBean msb = (MeetingSearchBean) form;

                conclutionsFilter = ("".equals(msb.getConclusionsFilter()) || msb.getConclusionsFilter() == null ? null : msb.getConclusionsFilter().trim());
                conclutionsOper = msb.getConclusionsOperator();

                dateIntervalEnd = ("".equals(msb.getDateIntervalEnd()) || msb.getDateIntervalEnd() == null ? null : msb.getDateIntervalEnd().trim());
                dateIntervalStart = ("".equals(msb.getDateIntervalStart()) || msb.getDateIntervalStart() == null ? null : msb.getDateIntervalStart().trim());

                meetingNameFilter = ("".equals(msb.getMeetingNameFilter()) || msb.getMeetingNameFilter() == null ? null : msb.getMeetingNameFilter().trim());
                meetingNameOper = msb.getMeetingNameOperator();

                orgNameFilter = ("".equals(msb.getOrgNameFilter()) || msb.getOrgNameFilter() == null ? null : msb.getOrgNameFilter().trim());
                orgNameOper = "".equals(msb.getOrgNameFilter()) || msb.getOrgNameFilter() == null ? null : msb.getOrgNameOperator().trim();

                orgInstFilter = msb.getOrgInstitutionFilter();
                orgITypeFilter = msb.getOrgITypeFilter();
                orgIFamilyFilter = msb.getOrgIFamilyFilter();
                orgIRegionFilter = msb.getOrgIRegionFilter();

                repNameFilter = ("".equals(msb.getRepNameFilter()) || msb.getRepNameFilter() == null ? null : msb.getRepNameFilter().trim());
                repNameOper = msb.getRepNameOperator();

                repInstFilter = msb.getRepInstitutionFilter();
                repITypeFilter = msb.getRepITypeFilter();
                repIFamilyFilter = msb.getRepIFamilyFilter();
                repIRegionFilter = msb.getRepIRegionFilter();

                venueFilter = ("".equals(msb.getVenueFilter()) || msb.getVenueFilter() == null ? null : msb.getVenueFilter().trim());
                venueOper = msb.getVenueOperator();


                orderByClause = resolveOrderBy(msb.getOrderByClause());

                //SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                startDate = null;
                endDate = null;

                try {
                    startDate = dateFormat.parse(dateIntervalStart);
                    endDate = dateFormat.parse(dateIntervalEnd);
                } catch (ParseException e) {
                    System.out.println("Could not pars date interval parameters");
                } catch (NullPointerException e) {
                    System.out.println("Could not pars date interval parameters");
                }

            }







            pager = new MeetingPager(meetingNameFilter,
                    meetingNameOper,
                    venueFilter,
                    venueOper,
                    conclutionsFilter,
                    conclutionsOper,
                    startDate,
                    endDate,
                    orgNameFilter,
                    orgNameOper,
                    orgInstFilter,
                    orgITypeFilter,
                    orgIFamilyFilter,
                    orgIRegionFilter,
                    orgIdFilter,
                    repNameFilter,
                    repNameOper,
                    repInstFilter,
                    repITypeFilter,
                    repIFamilyFilter,
                    repIRegionFilter,
                    repIdFilter,
                    orderByClause,
                    isQuickSearch);

            request.getSession().setAttribute(ConstantManager.SESSION_MEETING_PAGER, pager);


        } //user clicked on next or previous link so we get exsisting pager and us it
        else {
            pager = (MeetingPager) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PAGER);

            pager.setPageNumber(Integer.parseInt(pageNumber));


        }

        pager.doPaging(request);
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_MEETING_LIST);
        return actionForward;
    }

    private MeetingFacadeLocal lookupMeetingFacade() {
        try {
            Context c = new InitialContext();
            return (MeetingFacadeLocal) c.lookup("java:comp/env/MeetingFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }

    }

    private void injectAdvSearchBaseData(HttpServletRequest request) {

        List<Institution> institutions = lookupInstitutionFacade().findAll();
        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        List<InstitutionType> types = lookupInstitutionTypeFacade().findAll();
        List<InstitutionFamily> families = lookupInstitutionFamilyFacade().findAll();
        List<City> cities = lookupCityFacade().findAll();

        request.setAttribute("search_institutions", institutions);
        request.setAttribute("search_regions", regions);
        request.setAttribute("search_types", types);
        request.setAttribute("search_families", families);
        request.setAttribute("search_cities", cities);

    }

    private InstitutionFacadeLocal lookupInstitutionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFacadeLocal) c.lookup("java:comp/env/InstitutionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }

    }

    private CityFacadeLocal lookupCityFacade() {
        try {
            Context c = new InitialContext();
            return (CityFacadeLocal) c.lookup("java:comp/env/CityFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }

    }

    private InstitutionTypeFacadeLocal lookupInstitutionTypeFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionTypeFacadeLocal) c.lookup("java:comp/env/InstitutionTypeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }

    }

    private InstitutionRegionFacadeLocal lookupInstitutionRegionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionRegionFacadeLocal) c.lookup("java:comp/env/InstitutionRegionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }

    }

    private InstitutionFamilyFacadeLocal lookupInstitutionFamilyFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFamilyFacadeLocal) c.lookup("java:comp/env/InstitutionFamilyFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private String resolveOrderBy(String code) {
        if ("1".equals(code)) {
            code = "date DESC";
        } else if ("2".equals(code)) {
            code = "date ASC";
        } else if("3".equals(code)){
            code = "eventName";
        }  else if("4".equals(code)){
            code = "organizer.lastName";
        } else if("5".equals(code)){
            code = "institution.name";
        } else if("6".equals(code)){
            code = "venue";
        } else if("7".equals(code)){
            code = "status";
        }

        return code;

    }
}
